package pub.cleangao.memm.transport.netty.compress;

import net.jpountz.lz4.*;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

public class Lz4Compress implements Compress {

    @Override
    public byte[] compress(byte[] bytes) {
        try {
            LZ4Factory factory = LZ4Factory.fastestInstance();
            ByteArrayOutputStream byteOutput = new ByteArrayOutputStream();
            LZ4Compressor compressor = factory.fastCompressor();
            LZ4BlockOutputStream compressedOutput = new LZ4BlockOutputStream(byteOutput, 2048, compressor);
            compressedOutput.write(bytes);
            compressedOutput.close();
            return byteOutput.toByteArray();
        } catch (Exception e) {
            throw new RuntimeException("lz4 compress error", e);
        }
    }

    @Override
    public byte[] decompress(byte[] bytes) {
        try {
            LZ4Factory factory = LZ4Factory.fastestInstance();
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            LZ4FastDecompressor decompressor = factory.fastDecompressor();
            LZ4BlockInputStream in = new LZ4BlockInputStream(new ByteArrayInputStream(bytes), decompressor);
            int count;
            byte[] buffer = new byte[2048];
            while ((count = in.read(buffer)) != -1) {
                out.write(buffer, 0, count);
            }
            in.close();
            return out.toByteArray();
        } catch (Exception e) {
            throw new RuntimeException("lz4 decompress error", e);
        }
    }

    @Override
    public String type() {
        return CompressType.LZ4.getName();
    }
}
